package com.digitalchina.lxnsy.fragment;

import android.content.Intent;
import android.os.Bundle;
import android.os.Handler;
import android.os.Message;
import androidx.annotation.NonNull;
import androidx.swiperefreshlayout.widget.SwipeRefreshLayout;
import androidx.recyclerview.widget.LinearLayoutManager;
import android.view.LayoutInflater;
import android.view.View;
import android.view.ViewGroup;
import android.widget.TextView;

import com.afollestad.materialdialogs.DialogAction;
import com.afollestad.materialdialogs.MaterialDialog;
import com.digitalchina.lxnsy.R;
import com.digitalchina.lxnsy.activity.old.PostDemandActivity;
import com.digitalchina.lxnsy.activity.old.TalentsDetailsActivity;
import com.digitalchina.lxnsy.api.BusinessPersonnelService;
import com.digitalchina.lxnsy.base.BaseV4Fragment;
import com.digitalchina.lxnsy.constant.MSG;
import com.digitalchina.lxnsy.entity.PersonnelDemandVO;
import com.digitalchina.lxnsy.entity.ShareFarmListVO;
import com.digitalchina.lxnsy.interfaces.IMyNhbPos;
import com.digitalchina.lxnsy.toolkit.FastJsonUtil;
import com.digitalchina.lxnsy.toolkit.GotoUtil;
import com.digitalchina.lxnsy.toolkit.Utils;
import com.digitalchina.lxnsy.viewholder.PersonnelServiceHolder;
import com.digitalchina.lxnsy.xml.UserXML;
import com.jude.easyrecyclerview.EasyRecyclerView;
import com.jude.easyrecyclerview.adapter.BaseViewHolder;
import com.jude.easyrecyclerview.adapter.RecyclerArrayAdapter;

import java.io.Serializable;
import java.util.ArrayList;
import java.util.HashMap;
import java.util.List;
import java.util.Map;

import butterknife.Bind;
import butterknife.ButterKnife;
import butterknife.OnClick;

import static android.app.Activity.RESULT_OK;

/**
 * ================================================
 * 项目名称：BigData
 * 类描述：
 * 包名：com.digitalchina.bigdata.fragment
 * 创建人：郑皓
 * 创建时间：2017/9/8 15:41
 * 修改备注：
 * ================================================
 */
public class PersonnelDemandFragment extends BaseV4Fragment implements RecyclerArrayAdapter.OnLoadMoreListener, SwipeRefreshLayout.OnRefreshListener, IMyNhbPos {

    @Bind(R.id.recycler_view)
    EasyRecyclerView recyclerView;
    @Bind(R.id.tv_personnel)
    TextView tvPersonnel;

    private String postType = "";
    private RecyclerArrayAdapter adapter;
    private int page = 1;
    private int limit = 10;

    private List<PersonnelDemandVO> voList = new ArrayList<>();
    private String titleCode = "";
    private String countyCode = "";
    private String cityCode = "";
    private String lowPrice = "";
    private String highPrice = "";
    private Map<String, Object> map = new HashMap<>();
    private boolean myTalents;

    private int index = -1;

    @Override
    public void initMember() {
        if (getArguments() != null) {
            postType = getArguments().getString("postType");
            myTalents = getArguments().getBoolean("myTalents");


            if (postType == null)
                return;
            if (postType.equals("0")) {
                map.put("postType", "editSupply");
                tvPersonnel.setText("发布人力");
            } else {
                map.put("postType", "editDemand");
                tvPersonnel.setText("发布需求");
            }

            if (myTalents)
                tvPersonnel.setVisibility(View.VISIBLE);
            else
                tvPersonnel.setVisibility(View.GONE);

        }

        recyclerView.setLayoutManager(new LinearLayoutManager(getActivity()));

        recyclerView.addItemDecoration(Utils.setDividerDecoration(getActivity(), 10.0f, 0.0f, 0.0f));

        recyclerView.setAdapterWithProgress(adapter = new RecyclerArrayAdapter(getActivity()) {
            @Override
            public BaseViewHolder OnCreateViewHolder(ViewGroup parent, int viewType) {
                return new PersonnelServiceHolder(parent, myTalents, postType, PersonnelDemandFragment.this);
            }
        });

        onRefresh();
    }

    @Override
    public void addListener() {

        recyclerView.setRefreshListener(this);

        adapter.setMore(R.layout.view_more, this);

        adapter.setNoMore(R.layout.view_nomore);

        adapter.setError(R.layout.view_error, new RecyclerArrayAdapter.OnErrorListener() {
            @Override
            public void onErrorShow() {
                adapter.resumeMore();
            }

            @Override
            public void onErrorClick() {
                adapter.resumeMore();
            }
        });

        adapter.setOnItemClickListener(new RecyclerArrayAdapter.OnItemClickListener() {
            @Override
            public void onItemClick(int position) {
                PersonnelDemandVO vo = (PersonnelDemandVO) adapter.getAllData().get(position);
                vo.setMyTalents(myTalents);
                Map<String, Object> map = new HashMap<>();
                map.put("postType", postType); // 0是供应  1是需求
                map.put("vo", vo);
                GotoUtil.gotoActivity(getActivity(), TalentsDetailsActivity.class, "PersonnelDemandVO", map);
            }
        });

    }

    @Override
    public void setHandler() {

        mHandler = new Handler() {
            @Override
            public void handleMessage(Message msg) {
                super.handleMessage(msg);

                if (recyclerView == null) {
                    return;
                }
                if (recyclerView.getSwipeToRefresh().isRefreshing())
                    recyclerView.setRefreshing(false);

                switch (msg.what) {
                    case MSG.MSG_DEL_DEMAND_SUCCESS: // 删除
                        showToast("删除成功");
                        adapter.remove(index);
                        if (adapter.getAllData() != null && adapter.getAllData().size() <= 0)
                            recyclerView.showEmpty();
                        break;
                    case MSG.MSG_DEL_DEMAND_FIELD:
                        showToast(msg.obj + "");
                        break;
                    case MSG.MSG_GET_DEMAND_LIST_SUCCESS:
                        callBack(msg.obj);
                        break;
                    case MSG.MSG_GET_DEMAND_LIST_FIELD:
                        if (adapter.getAllData().size() > 0)
                            adapter.pauseMore();
                        else
                            recyclerView.showEmpty();
                        break;
                }
            }
        };

    }

    @Override
    public void callBack(Object object) {

        voList = FastJsonUtil.getListBeanRow(object.toString(), "rows", PersonnelDemandVO.class);

        if (voList == null)
            return;

        if (page == 1) { // 刷新
            adapter.clear();
        }

        adapter.addAll(voList);

        if (voList.size() < limit) {
            adapter.stopMore();
        }

    }

    @Override
    public void rightOnClick() {

    }

    @Override
    public View setRootView() {
        return inflate(R.layout.fragment_personnel_list);
    }

    @Override
    public View onCreateView(LayoutInflater inflater, ViewGroup container, Bundle savedInstanceState) {
        // TODO: inflate a fragment view
        View rootView = super.onCreateView(inflater, container, savedInstanceState);
        ButterKnife.bind(this, rootView);
        return rootView;
    }

    @Override
    public void onDestroyView() {
        super.onDestroyView();
        ButterKnife.unbind(this);
    }

    public void setValue(String titleCode, String cityCode, String countyCode, String lowPrice, String highPrice) {
        this.titleCode = titleCode;
        this.cityCode = cityCode;
        this.countyCode = countyCode;
        this.lowPrice = lowPrice;
        this.highPrice = highPrice;
        onRefresh();
    }


    @Override
    public void onRefresh() {
        page = 1;
        if (myTalents) {
            BusinessPersonnelService.getSupplyAndDemandList(getActivity(), String.valueOf(page), postType, "", "", lowPrice, highPrice, UserXML.getUserId(getContext()),"0",mHandler);
        } else {
            BusinessPersonnelService.getSupplyAndDemandList(getActivity(), String.valueOf(page), postType, "", "", lowPrice, highPrice, "","1",mHandler);
        }
    }

    @Override
    public void onLoadMore() {
        if (voList != null && voList.size() >= limit) {
            page++;
            if (myTalents) {
                BusinessPersonnelService.getSupplyAndDemandList(getActivity(), String.valueOf(page), postType, "", "", lowPrice, highPrice, UserXML.getUserId(getContext()),"0",mHandler);
            } else {
                BusinessPersonnelService.getSupplyAndDemandList(getActivity(), String.valueOf(page), postType, "", "", lowPrice, highPrice, "","1",mHandler);
            }
        }
    }

    @OnClick(R.id.tv_personnel)
    public void onViewClicked() {

        if (Utils.isLogin(getActivity())) {
            Intent intent = new Intent(getActivity(), PostDemandActivity.class);
            intent.putExtra("map", (Serializable) map);
            startActivityForResult(intent, 99);
        } else
            Utils.notLoginGoto(getActivity());
    }

    @Override
    public void onActivityResult(int requestCode, int resultCode, Intent data) {
        super.onActivityResult(requestCode, resultCode, data);
        if (requestCode == 99 && resultCode == RESULT_OK) {
            onRefresh();
        }
    }

    @Override
    public void del(final int pos) {
        index = pos;
        new MaterialDialog.Builder(getContext())
                .title("提示")
                .content("确定要删除该条信息？")
                .positiveText("删除")
                .negativeText("取消")
                .onPositive(new MaterialDialog.SingleButtonCallback() {
                    @Override
                    public void onClick(@NonNull MaterialDialog dialog, @NonNull DialogAction which) {
                        PersonnelDemandVO vo = (PersonnelDemandVO) adapter.getAllData().get(pos);
                        BusinessPersonnelService.deleteTalentDemand(getActivity(), vo.getId(), mHandler);
                    }
                })
                .show();
    }

    @Override
    public void edit(int pos) {
        Intent intent = new Intent(getActivity(), PostDemandActivity.class);
        map.put("data", adapter.getAllData().get(pos));
        intent.putExtra("map", (Serializable) map);
        startActivityForResult(intent, 99);
    }
}
